package com.example.community.login;

import com.example.community.dao.AdminsDao;
import com.example.community.dao.UsersDao;
import com.example.community.model.Admins;
import com.example.community.model.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/checkLogin")
public class CheckLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String loginId = req.getParameter("loginId");
        String pwd = req.getParameter("pwd");
        String usertype = req.getParameter("usertype");

        if (usertype.equals("isadmin")){
            if (CheckAdmin(loginId,pwd,req)){
                System.out.println("登录成功");
                resp.sendRedirect("index");
            }else {
                System.out.println("登录失败");
                req.getSession().setAttribute("loginMsg","登录失败");
                resp.sendRedirect("login");
            }
        }else if (usertype.equals("isuser")){
            if (CheckUser(loginId,pwd,req)){
                System.out.println("登录成功");
                resp.sendRedirect("userHomeServlet");
            }else {
                System.out.println("登录失败");
                req.getSession().setAttribute("loginMsg","登录失败");
                resp.sendRedirect("login");
            }
        }else {
            System.out.println("error");
        }
    }
    private boolean CheckAdmin(String loginId,String pwd,HttpServletRequest req){
        try {
            System.out.println("管理员登录");
            AdminsDao adminsDao = new AdminsDao();
            Admins admins = adminsDao.fandById(loginId);
            if (admins.getaPwd().equals(pwd)){
                req.getSession().setAttribute("currentUser",admins);
                return true;
            }else return false;
        }catch (Exception e){
            return false;
        }
    }

    private boolean CheckUser(String loginId,String pwd,HttpServletRequest req){
        try {
            System.out.println("用户登录");
            UsersDao usersDao = new UsersDao();
            Users users = usersDao.fandByAccount(loginId);
            if (users.getUsPwd().equals(pwd)){
                req.getSession().setAttribute("currentUser",users);
                req.getSession().setAttribute("currentUserUsNo",users.getUsNo());
                return true;
            }else return false;
        }catch (Exception e){
            return false;
        }
    }
}
